<?php
/**
 * Translation Search controller
 * 
 * @author Joseph Chereshnovsky <joseph.chereshnovsky@gmail.com>
 */
class Translation_SearchController extends Wise_Controller_Abstract
{
	/**
	 * Shows the search form and processes the search request
	 * 
	 * @return void
	 */
	public function indexAction()
	{
		$request = $this->getRequest();
		$search_phrase = $this->User->search_phrase;
		
		if ($request->isPost() || !empty($search_phrase)) {

			// If search form was submited then check if language pair is selected
	    	$source = $this->User->source_lang;
	    	$target = $this->User->target_lang;

			if ($request->isPost()) {

				// Save last search phrase
				$data = $request->getPost();
				$search_phrase = $data['search-field'];
				
				// Save search statistics
				$this['SearchStatistics']->saveStats($search_phrase, $source, $target);
				
				// Save search phrase for further use
				$this->User->search_phrase = $search_phrase;
			}
	    	
			if (empty($source) && empty($target)) {
				// redirect user to language pair selection if no language pair selected 
				$this->_redirect('/translation/pair');
			}
	    	
			// redirect to serach results page
	    	$this->_redirect('/translation/search/' . urlencode( trim($search_phrase) ) );
	   	}
	   	
	   	// If we have saved the last search phrase then pass it to the field and remove
	   	$this->view->search_phrase = $search_phrase;
		$this->User->search_phrase = '';
		
		// Build the list of popular tags
		$this->view->tags = $this['SearchStatistics']->getPopularSearches();
	}
	
	/**
	 * Shows search result
	 * 
	 * @return void
	 */
	public function resultAction()
	{
    	$req = $this->getRequest();

    	// Read required values
    	$searchPhrase = $req->getParam('keyword');

    	$termsList = $this['Translation']->searchTermsTranslation($searchPhrase);
		
		if (empty($termsList)) {
			// Save search statistics
		}
		
        $this->view->search_phrase	= $searchPhrase;
        $this->view->termsList		= $termsList;
        
   	   	// Remove session saved search phrase
   	   	// This means that search result for current phrase is showed up
   	   	// so we don't need to remember search phrase anymore
		$this->User->search_phrase = ''; 
	}
}